package com.azusa.ktc_base.service.impl;

import com.azusa.ktc_base.dao.CityDao;
import com.azusa.ktc_base.entity.City;
import com.azusa.ktc_base.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import utils.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(rollbackFor = {RuntimeException.class})
public class CityServiceImpl implements CityService {

    @Autowired
    private CityDao dao;

    @Override
    public List<City> findAll() {
        return dao.findAll();
    }

    @Override
    public Page<City> findPage(Integer page, Integer size) {
        PageRequest of = PageRequest.of(page, size);
        return dao.findAll(of);
    }

    @Override
    public City save(City city) {
        IdWorker worker = new IdWorker(1, 1);
        city.setId(worker.nextId() + "");
        return dao.save(city);
    }

    @Override
    public City findById(String id) {
        return dao.findById(id).get();
    }

    @Override
    public void deleteById(String id) {
        dao.deleteById(id);
    }

    @Override
    public List<City> findSearch(City city) {
        Specification<City> specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (city.getId() != null && !StringUtils.isEmpty(city.getId())){
                    predicateList.add(criteriaBuilder.equal(root.get("id").as(String.class),city.getId()));
                }
                if (city.getIshot() != null && !StringUtils.isEmpty(city.getIshot())){
                    predicateList.add(criteriaBuilder.equal(root.get("ishot").as(String.class),city.getIshot()));
                }
                if (city.getName() != null && !StringUtils.isEmpty(city.getName())){
                    predicateList.add(criteriaBuilder.like(root.get("name").as(String.class),city.getName()));
                }
                return criteriaQuery.where(criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]))).getRestriction();
            }
        };
        return dao.findAll(specification);
    }
}
